 
 
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
 
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
 
/**
 * @author 2262977944@qq.com
 * @version 1.0
 */
public class FreemarkerGeneratorUtil {
 
    private Template createTemplate(String templateName) throws IOException {
        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(Thread.currentThread().getContextClassLoader().getResource("templates/").getPath()));
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        configuration.setTemplateLoader(fileTemplateLoader);
        return configuration.getTemplate(templateName, "UTF-8");
    }
 
   
    public String generateToString(String templateName, Map<String, Object> templateData) throws IOException, TemplateException {
        StringWriter stringWriter = new StringWriter();
        Template template = createTemplate(templateName);
        template.process(templateData, stringWriter);
        stringWriter.flush();
        return stringWriter.toString();
    }
 
    private static FreemarkerGeneratorUtil freemarkerGeneratorUtil = null;
 
    public static synchronized FreemarkerGeneratorUtil getInstance() {
        if (freemarkerGeneratorUtil == null) {
            synchronized (FreemarkerGeneratorUtil.class) {
                if (freemarkerGeneratorUtil == null) {
                    freemarkerGeneratorUtil = new FreemarkerGeneratorUtil();
                }
            }
        }
        return freemarkerGeneratorUtil;
    }
}